import { NextRequest, NextResponse } from 'next/server';
import { mockTickets } from '@/mock/tickets';
import { Ticket, UpdateTicketRequest, ApiResponse } from '@/types/ticket';

// 模拟数据存储（与 /api/tickets 共享）
let tickets: Ticket[] = [...mockTickets];

// GET /api/tickets/[id] - 获取单个工单详情
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { id } = params;
    const ticket = tickets.find(t => t.id === id);

    if (!ticket) {
      return NextResponse.json(
        { success: false, message: '工单不存在' },
        { status: 404 }
      );
    }

    const response: ApiResponse<Ticket> = {
      success: true,
      data: ticket,
    };

    return NextResponse.json(response);
  } catch (error) {
    console.error('获取工单详情失败:', error);
    return NextResponse.json(
      { success: false, message: '获取工单详情失败' },
      { status: 500 }
    );
  }
}

// PUT /api/tickets/[id] - 更新工单
export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { id } = params;
    const body: UpdateTicketRequest = await request.json();

    const ticketIndex = tickets.findIndex(t => t.id === id);
    if (ticketIndex === -1) {
      return NextResponse.json(
        { success: false, message: '工单不存在' },
        { status: 404 }
      );
    }

    // 更新工单
    const updatedTicket: Ticket = {
      ...tickets[ticketIndex],
      ...body,
      updatedAt: new Date().toISOString(),
    };

    tickets[ticketIndex] = updatedTicket;

    const response: ApiResponse<Ticket> = {
      success: true,
      data: updatedTicket,
      message: '工单更新成功',
    };

    return NextResponse.json(response);
  } catch (error) {
    console.error('更新工单失败:', error);
    return NextResponse.json(
      { success: false, message: '更新工单失败' },
      { status: 500 }
    );
  }
}

// DELETE /api/tickets/[id] - 删除工单
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { id } = params;

    const ticketIndex = tickets.findIndex(t => t.id === id);
    if (ticketIndex === -1) {
      return NextResponse.json(
        { success: false, message: '工单不存在' },
        { status: 404 }
      );
    }

    // 删除工单
    tickets.splice(ticketIndex, 1);

    const response: ApiResponse<null> = {
      success: true,
      data: null,
      message: '工单删除成功',
    };

    return NextResponse.json(response);
  } catch (error) {
    console.error('删除工单失败:', error);
    return NextResponse.json(
      { success: false, message: '删除工单失败' },
      { status: 500 }
    );
  }
} 